<?php

namespace app\api\model\shop;


use app\api\model\UserConsumeLog;
use app\common\model\User;
use app\shopapi\model\Shop;
use app\shopapi\model\ShopAdmin;
use app\shopapi\model\ShopBills;
use think\Log;
use think\Model;
use think\Request;

class ShopDiscountOrder extends Model
{
    // 表名
    protected $name = 'shop_discount_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    public function calculate_discount($commission_rate)
    {
        $discount = (100-$commission_rate)/100;

        return $discount;
    }

    //计算用户返利
    public function calculate_rebate($commission_rate,$pay_price)
    {
        $rebate = (100-$commission_rate+$commission_rate*0.6)/100*$pay_price;

        $price = round($pay_price-$rebate,2);
        return $price;
    }

    public function refund($params)
    {
        $order_info = ShopDiscountOrder::where(['user_id'=>$params['user_id'],'order_id'=>$params['order_id']])->find();
        if (empty($order_info)){
            throw new \Exception('订单信息不存在');
        }

        $order_info->refund_no = $this->createRefundNo($order_info->order_id);
        $order_info->is_refund = 1;
        $order_info->refund_time = time();

        //执行原路退款
        $pay_model = new \app\shopapi\model\lakala\Pay();

        $refund_res = $pay_model->refund($order_info->lakala_order_no, $order_info->refund_no,$order_info->pay_price,$order_info->pay_seq_no);

        if ($refund_res['code']==0){
            throw new \Exception($refund_res['msg']);
        } else {
            if ($refund_res['data']['refund_status']=='2002'){
                throw new \Exception('退款失败');
            }
        }

        $res = $order_info->save();

        return $res;
    }

    /**
     * 创建退款流水号
     */
    public function createRefundNo($unique)
    {
        $no = createno('refund_no', '', $unique);
        return $no;
    }

    //创建折扣买单
    public function add($user_id,$shop_id,$pay_price,$remark,$pay_type,$type,$collect_money_remark,$collection_code)
    {
        if (empty($user_id))throw new \Exception('缺少参数用户id');

        if (empty($shop_id))throw new \Exception('缺少参数商户id');

        if (empty($pay_price))throw new \Exception('缺少参数付款金额');

        if (empty($pay_type))throw new \Exception('缺少参数付款方式');

        $order_model = new ShopDiscountOrder();

        $order_no = date("Ymdhis") . sprintf("%08d", $user_id) . mt_rand(1000, 9999);

        $shop = Shop::where(['shop_id'=>$shop_id])->field('shop_id,commission_rate,bank_name,bank,bank_num')->find();

        if ($type==1){
            $discount = self::calculate_discount($shop['commission_rate']);

            $rebate = self::calculate_rebate($shop['commission_rate'],$pay_price);//用户直接返利,例如付款100商品佣金比例为5,100-5+5*0.6/100=2,2是用户直接返利

            $shop_price = $pay_price*$discount;//商户直接得到的钱

            $commission_rate = $shop['commission_rate'];

            $commission = $pay_price*$commission_rate*0.6/100;//例如付款100商品佣金比例为5,100*5*0.6/100=3,3是可发放的佣金
        } else {
            $commission = 0;
            $rebate = 0;
            $shop_price = $pay_price;
        }
        $data = [
            'user_id'=>$user_id,
            'shop_id'=>$shop_id,
            'order_no'=>$order_no,
            'pay_price'=>$pay_price,
            'rebate'=>$rebate,
            'shop_price'=>$shop_price,
            'remark'=>$remark,
            'pay_type'=>$pay_type,
            'commission'=>$commission,
            'type'=>$type,
            'collect_money_remark'=>$collect_money_remark,
            'collection_code'=>$collection_code
        ];

        $res = $order_model->save($data);

        return $order_model;
    }

    //调起支付
    public function pay($order_no)
    {
        $order = ShopDiscountOrder::get(['order_no'=>$order_no]);

        $shop_info = Shop::get($order['shop_id']);

        $pay_model = new \app\shopapi\model\lakala\Pay();
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        $request = \think\Request::instance();

        $back_url = $request->root(true) . '/api/shop/shopdiscountorder/notify';

        $pay_price = intval($order['pay_price']*100);

        $amount = intval((100-$shop_info['commission_rate'])/100*$order['pay_price']*100);

        $split_list = [
            [
                'member_no'=>$shop_info['member_no'],
                'amount'=>$amount
            ]
        ];

        $data = [
            'shop_id'=>$order['shop_id'],
            'amount'=>$pay_price,
            'seller_member_no'=>$shop_info['member_no'],
            'user_id'=>$order['user_id'],
            'terminal_ip'=>$ip,
            'back_url'=>$back_url,
            'order_name'=>'折扣买单',
            'split_mode'=>1,
            'split_rule_data'=>$split_list
        ];

        $response = $pay_model->orderConsume($data);

        ShopDiscountOrder::update(['lakala_order_no'=>$response['order_no'],'pay_seq_no'=>$response['pay_seq_no']],['order_no'=>$order_no]);
        return $response;
    }

    public function notice_url($data,$event_type)
    {

        Log::error('折扣回调type:'.$event_type);
        $event = _json_decode($data,true);
        Log::error('折扣回调:'.json_encode($event,320));

        if ($event_type=='order.consume.pay'){
            $order_no = $event['order_no'];

            Log::error('折扣订单号:'.$order_no);
            //$out_order_no = $event['out_order_no'];

            $pay_status = $event['pay_status'];
            $pay_amount = $event['pay_amount']/100;
            $pay_time = $event['pay_time'];
            $status = $event['status'];
            $third_party_payment = $event['third_party_payment'];
            $split_seq_no =  isset($event['split_seq_no'])? $event['split_seq_no']:'';

            if ($status=='OK'){
                if ($pay_status==1004){
                    //$pay_amount = $event['pay_amount']/100;
                    //已付款
                    $order = ShopDiscountOrder::get(['lakala_order_no'=>$order_no]);
                    if ($order->pay_status==1){
                        return true;
                    }
                    //音响播报
                    $model = new \app\shopapi\model\Sound();
                    //$content = $pay_amount;
                    $content = '哇哇来购收款'.$pay_amount.'元';
                    $model->multiInvoke($content,$order->shop_id);

                    $order->pay_status = 1;
                    $order->pay_time = strtotime($pay_time);
                    $order->third_party_payment = $third_party_payment;
                    $order->split_seq_no = $split_seq_no;
                    $order->save();
                    return true;
                }
            }
        } elseif ($event_type=='order.channel.fee'){
            $channel_fee = $event['channel_fee']/100;
            $order_no = $event['order_no'];
            $trade_amount = $event['trade_amount']/100;
            $order_status = $event['order_status'];

            $order = ShopDiscountOrder::get(['lakala_order_no'=>$order_no]);

            $third_party_payment = $order->third_party_payment;

            if ($order->pay_status==1&&$order_status==1004&&$order->channel_fee==0){

                $bills_detail = ShopBills::where(['order_no'=>$order_no])->find();
                if ($bills_detail)return false;

                $shop = Shop::where(['shop_id'=>$order->shop_id])
                    ->field('shop_id,shop_name,commission_rate,bank_name,bank,bank_num,banner_img,member_no,commission_rate')
                    ->find();

                //增加商户账单
                $bills_model = new ShopBills();
                $worker_id = 0;

                if ($order->collection_code){
                    $shop_admin = ShopAdmin::get(['collection_code'=>$order->collection_code,'is_applicant'=>0]);
                    $worker_id = $shop_admin?$shop_admin->id:0;
                }
                $consume_type = $order->getAttr('type');//1是折扣买单,0线下买单
                $bills_model->add([
                    'user_id'=>$order->user_id,
                    'shop_id'=>$order->shop_id,
                    'pay_price'=>$trade_amount,
                    'pay_type'=>$third_party_payment,
                    'trans_oktime'=>$order->pay_time,
                    'consume_type'=>$consume_type,
                    'order_no'=>$order_no,
                    'service_charge'=>$channel_fee,
                    'worker_id'=>$worker_id,
                    'remark'=>$order->remark,
                    'collect_money_remark'=>$order->collect_money_remark,
                ]);

                //分账
                $pay_model = new \app\shopapi\model\lakala\Pay();
                $out_request_no = date("YmdHis") . sprintf("%08d", 12) . mt_rand(1000, 9999);

                //增加消费记录
                //1是折扣买单,0线下买单
                if ($consume_type==1){
                    $type = 1;
                    $lockMemberType = 1;
                    $total_commission = $order->commission+$order->rebate;
                    $commission = $order->rebate;
                    $amount = intval((100-$shop['commission_rate'])/100*$order['pay_price']*100);
                    $amount = intval($amount+$channel_fee*100);
                    $total_amount = intval($order['pay_price']*100);
                    $pay_price = intval($order['pay_price']*100);
                    //$shop_price =  bcsub($pay_price,$amount,0);
                    $shop_price = intval($pay_price-$amount);
                    $split_list = [
                        [
                            'member_no'=>$shop['member_no'],
                            'amount'=>$amount
                        ],
                        [
                            'member_no'=>'7262709383570984960',
                            'amount'=>$shop_price
                        ]
                    ];
                } else {
                    $type = 0;
                    $lockMemberType = 2;
                    $total_commission = $trade_amount*0.0012;
                    $commission = 0;

                    //$amount = intval($order['pay_price']*100);
                    $amount = intval($order['pay_price']*100);
                    $total_amount = intval($order['pay_price']*100);
                    $shop_price =  intval($channel_fee*100);
                    $split_list = [
                        [
                            'member_no'=>$shop['member_no'],
                            'amount'=>$amount
                        ],
                        /*[
                            'member_no'=>'7262709383570984960',
                            'amount'=>0
                        ]*/
                    ];
                }
                //商户分的金额
                $fenzhang_res = $pay_model->orderComplete($order_no,$shop['member_no'],$out_request_no,$total_amount,$split_list);

                Log::error('分账回调:'.json_encode($fenzhang_res,320));
                $consume_log_info = UserConsumeLog::get([ 'user_id'=>$order->user_id,'order_no'=>$order_no]);

                if (!$consume_log_info){
                    $request = Request::instance();
                    $domain=$request->domain();
                    $consume_log_model = new UserConsumeLog();
                    $image = $domain.explode(',',$shop['banner_img'])[0];
                    $consume_log_data = [
                        'user_id'=>$order->user_id,
                        'title'=>'【买单】 消费'.$trade_amount.'元',
                        'shop_id'=>$shop['shop_id'],
                        'shop_name'=>$shop['shop_name'],
                        'image'=>$image,
                        'order_no'=>$order_no,
                        'pay_time'=>$order->pay_time,
                        'pay_price'=>$trade_amount,
                        'consume_type'=>$consume_type,//0=>'线下买单',1=>'折扣买单'
                        'commission'=>$commission,
                        'total_commission'=>$total_commission,
                        'order_status_name'=>'已付款',
                        'pay_type'=>$third_party_payment
                    ];
                    User::update(['is_buy'=>1],['id'=>$order->user_id]);
                    $user_model = new User();
                    $user_model->upgrade($order->user_id);
                    $consume_log_model->save($consume_log_data);
                    Log::error('总佣金'.$consume_log_model->total_commission);
                    if ($consume_log_model->total_commission>0){
                        Log::error($consume_log_model->consume_id);
                        Log::error($type);
                        UserConsumeLog::lockMemberConsumeCalculate($order->user_id,$consume_log_model->total_commission,$consume_log_model->consume_id,$lockMemberType);
                        UserConsumeLog::newrecommendShopConsumeCalculate($order->user_id,$order->shop_id,$consume_log_model->total_commission,$consume_log_model->consume_id,$type);
                        UserConsumeLog::recommendShopConsumeCalculate($order->user_id,$order->shop_id,$consume_log_model->total_commission,$consume_log_model->consume_id,$type);
                        //发放收益
                        //UserConsumeLog::sendCommission($order_no);
                    }

                }
                if ($order->pay_price>=3){
                    ShopFans::add($order->user_id,$order->shop_id);
                }

            }

            $order->channel_fee = $channel_fee;

            $order->save();

            return true;
        }
    }

    //支付回调
    public function old_notice_url($data,$event_type)
    {
        Log::error('折扣回调type:'.$event_type);
        $event = _json_decode($data,true);
        Log::error('折扣回调:'.json_encode($event,320));
        if ($event_type=='order.consume.pay'){
            $order_no = $event['order_no'];

            Log::error('折扣订单号:'.$order_no);
            $out_order_no = $event['out_order_no'];
            //$seller_member_no = $event['seller_member_no'];
            //$amount = $event['amount'];

            //$order_status = $event['order_status'];
            $pay_status = $event['pay_status'];
            //$pay_seq_no = $event['pay_seq_no'];
            $pay_time = $event['pay_time'];
            $status = $event['status'];
            $third_party_payment = $event['third_party_payment'];

            if ($status=='OK'){
                if ($pay_status==1004){
                    $pay_amount = $event['pay_amount']/100;
                    //已付款
                    $order = ShopDiscountOrder::get(['lakala_order_no'=>$order_no]);
                    if ($order->pay_status==1){
                        return true;
                    }
                    $order->pay_status = 1;
                    $order->pay_time = strtotime($pay_time);
                    $order->save();
                    $shop = Shop::where(['shop_id'=>$order->shop_id])
                        ->field('shop_id,shop_name,commission_rate,bank_name,bank,bank_num,banner_img')
                        ->find();

                    //增加商户账单
                    $bills_model = new ShopBills();
                    //$bills_model->add($order->user_id,$order->shop_id,$pay_amount,$third_party_payment,strtotime($pay_time),1,$order_no,0);
                    $worker_id = 0;
                    if ($order->collection_code){
                        $shop_admin = ShopAdmin::get(['collection_code'=>$order->collection_code,'is_applicant'=>0]);
                        $worker_id = $shop_admin->id;
                    }
                    $bills_model->add([
                        'user_id'=>$order->user_id,
                        'shop_id'=>$order->shop_id,
                        'pay_price'=>$pay_amount,
                        'pay_type'=>$third_party_payment,
                        'trans_oktime'=>strtotime($pay_time),
                        'consume_type'=>$order->getAttr('type'),
                        'order_no'=>$order_no,
                        'service_charge'=>0,
                        'worker_id'=>$worker_id,
                        'remark'=>$order->remark,
                        'collect_money_remark'=>$order->collect_money_remark,
                    ]);
                    //增加消费记录
                    $total_commission = $order->commission;
                    $commission = $order->rebate;
                    $consume_log_info = UserConsumeLog::get([ 'user_id'=>$order->user_id, 'order_no'=>$order_no]);

                    if (!$consume_log_info){
                        $request = Request::instance();
                        $domain=$request->domain();
                        $consume_log_model = new UserConsumeLog();
                        $image = $domain.explode(',',$shop['banner_img'])[0];
                        $consume_log_data = [
                            'user_id'=>$order->user_id,
                            'title'=>'【买单】 消费'.$pay_amount.'元',
                            'shop_id'=>$shop['shop_id'],
                            'shop_name'=>$shop['shop_name'],
                            'image'=>$image,
                            'order_no'=>$order_no,
                            'pay_time'=>strtotime($pay_time),
                            'pay_price'=>$pay_amount,
                            'consume_type'=>1,
                            'commission'=>$commission,
                            'total_commission'=>$total_commission,
                            'order_status_name'=>'已付款',
                            'pay_type'=>$third_party_payment
                        ];
                        User::update(['is_buy'=>1],['id'=>$order->user_id]);
                        $user_model = new User();
                        $user_model->upgrade($order->user_id);
                        $consume_log_model->save($consume_log_data);
                        UserConsumeLog::lockMemberConsumeCalculate($order->user_id,$consume_log_model->total_commission,$consume_log_model->consume_id,1);
                        UserConsumeLog::recommendShopConsumeCalculate($order->user_id,$order->shop_id,$consume_log_model->total_commission,$consume_log_model->consume_id,1);
                        //发放收益
                        UserConsumeLog::sendCommission($order_no);
                    }

                    //音响播报
                    $model = new \app\shopapi\model\Sound();
                    $content = '收款'.$pay_amount.'元';
                    $model->multiInvoke($content,$order->shop_id);
                }
            }
        } elseif ($event_type=='order.channel.fee'){
            $order_no = $event['order_no'];
            $request_no = $event['request_no'];
            $request_status = $event['request_status'];
            $channel_fee = $event['channel_fee'];
            $trade_amount = $event['trade_amount'];

            //$order = ShopDiscountOrder::get(['lakala_order_no'=>$order_no]);
            ShopBills::update(['service_charge'=>$channel_fee/100],['order_no'=>$order_no]);

        }




        return true;
    }


}